package com.rom.ratethehell;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;

import com.rom.ratethehell.entities.Comment;
import com.rom.ratethehell.entities.Picture;
import com.rom.ratethehell.entities.RatePicture;
import com.rom.ratethehell.entities.ServerResponse;
import com.rom.ratethehell.protocol.PictureHandler;
import com.rom.ratethehell.protocol.RequestOrganizer;
import com.rom.ratethehell.protocol.ServerResponseListener;
import com.rom.ratethehell.protocol.tasks.RandomPictureTask;
import com.rom.ratethehell.protocol.tasks.SneakAPicTask;
import com.rom.ratethehell.rate.custom_views.CommentView;

public class RateActivity extends Activity {

	private ProgressBar pb;
	private Button sendButton;
	private TextView text;
	private ListView listOfComments;
	private ImageSwitcher imageToRate;
	private ProgressDialog dialog;
	private Animation slideOut;
	private Animation slideIn;
	private static ImageView image0,image1;
	protected static RatePicture picture0,picture1,which;
	private static final Bitmap EMPTY_BITMAP =Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
	public static final String RATE_INTENT_PIC_ID_KEY = "picId";
	@SuppressLint("WrongViewCast")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_rate);
		pb = (ProgressBar) findViewById(R.id.rate_bar);
		sendButton = (Button) findViewById(R.id.send_rate);
		text = (TextView)findViewById(R.id.rating_result);
		listOfComments = (ListView) findViewById(R.id.listView);
		imageToRate = (ImageSwitcher) findViewById(R.id.picture_switcher);

		image0=(ImageView) findViewById(R.id.imageView1);
		image1 =(ImageView) findViewById(R.id.imageView2);
		slideOut = AnimationUtils.loadAnimation(this,  
                android.R.anim.slide_out_right);
		slideIn = AnimationUtils.loadAnimation(this,  
                android.R.anim.slide_in_left);
		imageToRate.setInAnimation(slideIn);  
		imageToRate.setOutAnimation(slideOut);  
		imageToRate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				next();
			}
		});
		sendButton.setVisibility(View.INVISIBLE);
		invokeInit();
		text.setVisibility(View.INVISIBLE);
		sendButton.setOnClickListener(new OnClickListener() {
			
			private boolean isShowingResult = true;

			@Override
			public void onClick(View v) {
				
				if (!isShowingResult) {
					next();
				} else {
					findViewById(R.id.rate_bar).setVisibility(View.INVISIBLE);
					text.setVisibility(View.VISIBLE);
					text.setText(which.getNewRating(pb.getProgress())+"");
					sendButton.setText(R.string.action_rate_continue);
					RequestOrganizer.getInstance().sendRate(which.getId(),pb.getProgress());
				}
				isShowingResult=!isShowingResult;
			}
			
		});
		
	}
	private void invokeInit() {
		(new SneakAPicTask<Void>(this) {


			
			@Override
			protected void onSuccess(Void result) {
				image0.setImageBitmap(which.getBitmap());
				image1.setImageBitmap(EMPTY_BITMAP);
				pb.setProgress(which.getRating().intValue());
				listOfComments.setAdapter(new CommentsAdapter(RateActivity.this,which.getId(),which.getComments()));
				sendButton.setVisibility(View.VISIBLE);
				imageToRate.requestFocus();
			}

			@Override
			protected void doTask() throws Exception {
				PictureHandler instance = PictureHandler.getInstance();
				long id;
				if ((id=getIntent().getLongExtra(RATE_INTENT_PIC_ID_KEY, -1))!=-1) 
					picture0 = instance.getSpecificPic(id);
				else picture0 = instance.getNextPic();
				picture1 = instance.getNextPic();
				which = picture0;
				getIntent().putExtra("firstTime?", false);
			}
		}).execute();
	}
	public void next () {
		final PictureHandler instance = PictureHandler.getInstance();
		RandomPictureTask randomPictureTask = new RandomPictureTask(this) {
			
			@Override
			protected void onSuccess(RatePicture result) {
				switchTo(result);
			}
			
		};
		if (instance.available()) {
			try {
				switchTo(instance.getNextPic());
			} catch (IOException e1) {
				randomPictureTask.execute();
			}
		} else randomPictureTask.execute();
		
	}
	
	public void switchTo(RatePicture result) {
		setRatePicture(result);
		sendButton.setText(R.string.action_rate_send);
		text.setVisibility(View.INVISIBLE);
		findViewById(R.id.rate_bar).setVisibility(View.VISIBLE);
		imageToRate.requestFocus();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.rate, menu);
		return true;
	}
	private void setRatePicture(RatePicture newPic) {
		imageToRate.showNext();
		if (which==picture1){
			picture0.getBitmap().recycle();
			picture0=newPic;
			image0.setImageBitmap(newPic.getBitmap());
			slideOut.setAnimationListener(new AnimationListener() {
				
				@Override
				public void onAnimationStart(Animation animation) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onAnimationRepeat(Animation animation) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onAnimationEnd(Animation animation) {
					image1.setImageBitmap(EMPTY_BITMAP);
				}
			});
			which=picture0;
		} else {
			picture1.getBitmap().recycle();
			picture1=newPic;
			image1.setImageBitmap(newPic.getBitmap());
			slideOut.setAnimationListener(new AnimationListener() {
				
				@Override
				public void onAnimationStart(Animation animation) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onAnimationRepeat(Animation animation) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onAnimationEnd(Animation animation) {
					image0.setImageBitmap(EMPTY_BITMAP);
				}
			});
			which=picture1;
		}
		listOfComments.setAdapter(new CommentsAdapter(this,newPic.getId(),newPic.getComments()));
		imageToRate.requestFocus();
		
	}
	
}
